<template>
  <view class="container">
    <view class="content">
      <view class="xjs-ml-32 xjs-mr-32">
        <view class="top_box">
          <view class="xjs-size-32 xjs-weight-bold">{{ orderInfo.goodsName }}</view>
          <view class="time_box">
            每次{{ orderInfo.goodsSkuServiceTime }}｜共服务{{ orderInfo.serviceDays }}天｜宠物{{ orderInfo.petNum }}只
          </view>
        </view>
        <view class="label_box">
          <view class="label_name">订单原价</view>
          <view class="original_text">¥{{ orderInfo.payAmount }}</view>
        </view>
        <view class="label_box">
          <view class="label_name">改价方式</view>
          <view class="lf lf-center" @click="changeType(1)">
            <image class="act_img"
                   :src="discountInfo.type==1?'https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-59.png':'https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-60.png'"></image>
            <view>按金额</view>
          </view>
          <view class="lf lf-center discount" @click="changeType(2)">
            <image class="act_img"
                   :src="discountInfo.type==2?'https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-59.png':'https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-60.png'"></image>
            <view>按折扣</view>
          </view>
        </view>
        <view class="label_box">
          <view class="label_name">{{ discountInfo.type == 1 ? '改后金额' : '折扣' }}</view>
          <view class="ipt_box">
            <input class="xjs-pl-24 input_money" placeholder-style="font-weight: normal;" @input="discountInputChange"
                   @blur="discountInputBlur"
                   :placeholder="discountInfo.type==1?'输入金额':'输入折扣(0.01-9.99)'"
                   v-model="discountInfo.inputValue" type="digit"/>
            <text class="xjs-ml-32 xjs-mr-32">{{ discountInfo.type == 1 ? '元' : '折' }}</text>
          </view>
        </view>
        <view class="label_box1" v-if="discountInfo.type===2">
          <view class="label_name">改后金额</view>
          <view>
            <view class="number_text">¥{{ discountInfo.payAmount }}</view>
            <text class="bottom_text">改后金额=订单原价*优惠折扣</text>
          </view>
        </view>
        <view class="price_adjustment_box">
          <view class="adjustment_label">改后收益</view>
          <view class=" adjustment_value">
            <view class="xjs-btn-primary compute_btn" @click="calculateIncome()">开始计算</view>
            <view class="income_text" v-if="Number(incomeInfo.studioSharing)">工作室接单服务费 ¥{{
                incomeInfo.studioSharing
              }}
            </view>
            <view class="income_text" v-if="Number(incomeInfo.income)">服务人员收益 ¥{{ incomeInfo.income }}</view>
            <view class="income_text" v-if="Number(incomeInfo.promotionSharing)">推广人员收益
              ¥{{ incomeInfo.promotionSharing }}
            </view>
          </view>
        </view>
      </view>
    </view>
    <view
        :class="['xjs-btn-primary',discountInfo.inputValue===''?'xjs-btn-disabled':'','btn_box']"
        @click="confirmChange()">确认修改
    </view>
  </view>
</template>

<script setup lang="ts">
import {onLoad} from "@dcloudio/uni-app";
import {nextTick, reactive, ref} from "vue";
import BigNumber from "bignumber.js";
import api from '@/api/index';
import {debounce} from '@/hooks/useFunction'


let orderInfo = reactive(<{
  id: string,
  goodsName: string,
  serviceDays: string,
  payAmount: string,
  petNum: string,
  goodsSkuServiceTime: string,
}>{
  id: '',
  goodsName: '',
  serviceDays: '',
  payAmount: '',
  petNum: '',
  goodsSkuServiceTime: '',
})
let discountInfo = reactive(<{
  type: number,
  inputValue: number | string,
  discount: number | string,
  payAmount: number | string,
  discountAmount: number | string
}>{
  type: 1,
  inputValue: "",
  discount: '',
  payAmount: '',
  discountAmount: ''
})
let incomeInfo = reactive({})
const changeType = (type: number) => {
  discountInfo.inputValue = '';
  discountInfo.discount = '';
  discountInfo.type = type;
  discountInfo.payAmount = ''
  discountInfo.discountAmount = ''
}
const discountInputChange = (e) => {
  // incomeInfo = {}
  nextTick(() => {
    let value = e.detail.value
    // 如果当前输入为空，直接允许清空
    if (!value) {
      discountInfo.inputValue = ''
    } else if (value?.charAt(0) === '0' && value.charAt(1) && value.charAt(1) !== '.') {
      // // 1. 当第一位为0时，只能输入小数点【第二位必须是小数点】
      value = '0'
    }
    value = value.replace(/[^\d.]/g, '') // 清除"数字"和"."以外的字符
    value = value.replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
    value = value.match(/^\d*(\.?\d{0,2})/g)[0] || '' // 保留2位小数
    discountInfo.inputValue = value
    if (discountInfo.type == 1) {
      if (Number(value) >= Number(orderInfo.payAmount)) {
        value = orderInfo.payAmount
        discountInfo.inputValue = value
      }
      discountInfo.discount = value
      discountInfo.payAmount = discountInfo.inputValue
      discountInfo.discountAmount = new BigNumber(orderInfo.payAmount).minus(value || 0).toNumber();
    } else {
      if (Number(value) >= 9.99) {
        value = 9.99
        discountInfo.inputValue = value
      }
      // if (Number(value) <= 0.01) {
      //   value = 0.01
      //   discountInfo.inputValue = value
      // }
      let payAmount = new BigNumber(Number(orderInfo.payAmount)).times(new BigNumber(value || 0).div(10)).toNumber().toFixed(2)
      discountInfo.discount = e.detail.value
      discountInfo.payAmount = payAmount;
      discountInfo.discountAmount = new BigNumber(Number(orderInfo.payAmount)).minus(discountInfo.payAmount).toNumber();
    }
  })

}
// 计算收益
const calculateIncome = async () => {
  const res = await api({
    method: 'post',
    url: `/mall/order/calcIncome`,
    contentType: 'json',
    data: {
      id: orderInfo.id,
      payAmount: discountInfo.payAmount,
    }
  })
  if (res.code == 0) {
    Object.assign(incomeInfo, res.data)
    console.log(incomeInfo, 'incomeInfo');
  } else {
    uni.showToast({
      title: res.msg,
      icon: 'none'
    })
  }
}
const discountInputBlur = (e) => {
  // let value = e.detail.value
  // if (value.indexOf(".") > 0) {
  //   let str = value.slice(
  //       value.indexOf("."),
  //       value.length
  //   );
  //   if (str / 1 <= 0) {
  //     value = value.replace(str, "");
  //   }
  // }
  // value = Number(value)
  // discountInfo.inputValue = Number(value);
}
//  防抖
const debounceBtn = debounce()
const confirmChange = async () => {
  debounceBtn(async () => {
    console.log(discountInfo.discount, 'discountInfo.discount');
    if (discountInfo.type == 1) {
      if (discountInfo.discount === '') {
        uni.showToast({
          title: '请输改后金额',
          icon: 'none'
        })
        return;
      }
      if (Number(discountInfo.discount) == 0) {
        uni.showToast({
          title: '改后金额不能为0',
          icon: 'none'
        })
        return;
      }
    } else {
      if (discountInfo.discount === '') {
        uni.showToast({
          title: '请输入优惠折扣',
          icon: 'none'
        })
        return;
      }
      if (Number(discountInfo.discount) == 0) {
        uni.showToast({
          title: '优惠折扣在0.01-9.99之间',
          icon: 'none'
        })
        return;
      }
    }
    let params = reactive({
      id: orderInfo.id,
      discount: discountInfo.discount,
      payAmount: Number(discountInfo.payAmount),
      discountAmount: discountInfo.discountAmount,
    })
    if (discountInfo.type == 1) {
      params.discount = '';
    }
    const res = await api({
      method: 'post',
      url: `/mall/order/changePrice`,
      contentType: 'json',
      data: params
    })
    if (res.code == 0) {
      uni.showToast({
        title: '修改成功',
        icon: 'none',
      })
      uni.navigateBack({delta: 1});
    }
  })


}
onLoad((options) => {
  orderInfo.id = options.id;
  orderInfo.goodsName = options.goodsName;
  orderInfo.serviceDays = options.serviceDays;
  orderInfo.payAmount = options.payAmount;
  orderInfo.petNum = options.petNum;
  orderInfo.goodsSkuServiceTime = options.goodsSkuServiceTime;

})
</script>

<style lang="scss" scoped>
.lf {
  display: flex;
}

.lf-between {
  justify-content: space-between;
}

.lf-center {
  align-items: center;
}

.container {
  box-sizing: border-box;
  padding-bottom: var(--safe-area-bottom);
}

.content {
  font-size: 30rpx;
  border-radius: 24rpx;
  background-color: #ffffff;
  margin: 32rpx;
  padding-bottom: 64rpx;

  .top_box {
    padding: 64rpx 0;
    border-bottom: 1rpx solid #E6E6E6;
  }

  .time_box {
    margin-top: 16rpx;
    font-size: 26rpx;
    color: #7C807F;
  }

  .label_box {
    display: flex;
    align-items: center;
    margin-top: 64rpx;

  }

  .label_box1 {
    display: flex;
    margin-top: 64rpx;
  }

  .ipt_box {
    display: flex;
    align-items: center;
    background-color: #F5F6F7;
    width: 462rpx;
    height: 84rpx;
    border-radius: 16rpx;
  }

  .label_name {
    width: 136rpx;
    font-size: 26rpx;
    font-weight: bold;
    margin-right: 24rpx;
  }

  .input_money {
    font-weight: bold;
  }

  .discount {
    margin-left: 96rpx;
  }

  .original_text {
    color: #CACCCC;
    font-size: 32rpx;
  }

  .act_img {
    width: 36rpx;
    height: 36rpx;
    border-radius: 50%;
    margin-right: 18rpx;
  }

  .number_text {
    color: #FF6084;
    font-size: 32rpx;
    padding-bottom: 24rpx;
  }

  .bottom_text {
    color: #7C807F;

  }
}

.btn_box {
  width: 686rpx;
  margin-top: 40rpx;
  margin-left: 32rpx;
}

.price_adjustment_box {
  display: flex;
  margin-top: 64rpx;

  .adjustment_label {
    width: 136rpx;
    font-weight: bold;
    font-size: 26rpx;
    color: #1B2120;
    margin-right: 24rpx;
  }

  .adjustment_value {
    .compute_btn {
      width: 152rpx;
      height: 58rpx;
      font-size: 26rpx;
    }

    .income_text {
      font-weight: 400;
      font-size: 26rpx;
      color: #7C807F;
      margin-top: 24rpx;
    }
  }
}
</style>